/*************************************************************************
    > File Name: read_profs_pidmax.c
    > Author:		
    > Mail:		
    > Created Time: 2021年03月23日 星期二 11时25分55秒
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define BUF_SIZE 100
/* will not write success, the file node is reade only */
#define PID_MAX "/proc/sys/kernel/pid_max"

int main(int argc, char *argv[])
{

	int fd, rcnt, wcnt;
	char buf[BUF_SIZE];

	/* open pid_max in proc */
	fd = open(PID_MAX, argc > 1?O_RDWR:O_RDONLY);
	if (fd == -1) {
		perror(strerror(errno));
		exit(-1);
	}

	/* read fd to buf */
	rcnt = read(fd, buf, BUF_SIZE);
	if (rcnt < 0) {
		goto err;
	}
	/* the buf string contained the '\n' from the fd */
	printf("Old value:%s", buf);

	if (argc > 1) {
		/* update a new number */
		wcnt = strlen(argv[1]);
		rcnt = write(fd, argv[1], wcnt);
		if (wcnt != rcnt) {
			goto err;
		}
#if 1

		/* read a new number to buf */
		rcnt = read(fd, buf, BUF_SIZE);
		if (rcnt < 0) {
			goto err;
		}
		printf("New value:%s", buf);
#else
	system("cat /proc/sys/kernel/pid_max");
#endif
	}

	close(fd);
	return 0;

err:
		perror(strerror(errno));
		close(fd);
		exit(-1);
}
